package com.corejsf;

import java.io.Serializable;
import java.util.Date;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;

@Named("user")
@SessionScoped
public class User implements Serializable {
	
	// domain fields
	private String nick;
	private String pass;
	private UserLevel level;
	private int id;
	
	// bean fields
	private Category openCategory;
	private Thread openThread;
	private String title;
	private String content;
	
	public User() {
		nick = "";
		pass = "";
		level = null;
		id = 0;
	}
	
	@Inject
	private Dao d;
	
	@Inject
	private Service s;
	
	public String getNick() {
		return nick;
	}
	public void setNick(String nick) {
		this.nick = nick;
	}
	public String getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}
	public UserLevel getLevel() {
		return level;
	}
	public void setLevel(UserLevel level) {
		this.level = level;
	}
	public Category getOpenCategory() {
		return openCategory;
	}
	public void setOpenCategory(Category openCategory) {
		this.openCategory = openCategory;
	}
	public Thread getOpenThread() {
		return openThread;
	}
	public void setOpenThread(Thread openThread) {
		this.openThread = openThread;
	}
	
	public void submit() {
		if(openThread == null && openCategory != null) {
			Thread t = new Thread();
			t.setCat(openCategory);
			Post p = new Post();
			p.setTitle(title);
			p.setContent(content);
			p.setAuthor(this);
			p.setTimeStamp(new Date());
			t.addPost(p);
			d.createThread(t);
			p.setThreadId(t.getId());
		} else if(openThread != null && openCategory != null){
			Post p = new Post();
			p.setAuthor(this);
			p.setContent(content);
			p.setTitle(title);
			p.setTimeStamp(new Date());
			p.setThreadId(openThread.getId());
			d.createPost(p);
		} else if(openThread == null && openCategory == null) {
			Category c = new Category();
			c.setName(title);
			d.createCategory(c);
		}
		title = "";
		content = "";
	}
	
	public String reset() {
		openCategory = null;
		openThread = null;
		return "index";
	}
	
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public boolean renderLogin() {
		return level == null;
	}
	public boolean canPost() {
		return level != null;
	}
	public boolean canDelete() {
		if(level == UserLevel.ADMIN || level == UserLevel.MOD || level == UserLevel.DINMOR) {
			return true;
		} else {
			return false;
		}
	}
	public boolean canUpdateCat() {
		if(level == UserLevel.ADMIN || level == UserLevel.DINMOR) {
			return true;
		} else {
			return false;
		}
	}
}
